# -*- coding: utf-8 -*-
# @Time    : 2019/10/21 17:16
# @Author  : 岳保保
# @File    : ResultResponse.py
# @Software: PyCharm
from django.http import JsonResponse

from utils.utils.PagePaginationUtils import PagePagination


class ResultResponse:
    """
    常规返回
    """

    def __init__(self, flag=True, code=10000, msg='操作成功'):
        self.flag = flag
        self.code = code
        self.msg = msg

    @property
    def response(self):
        return JsonResponse({
            "success": self.flag,
            "code": self.code,
            "message": self.msg
        }, json_dumps_params={'ensure_ascii': False})

    def data_response(self, data):
        return JsonResponse({
            "success": self.flag,
            "code": self.code,
            "message": self.msg,
            "data": data
        }, safe=False, json_dumps_params={'ensure_ascii': False})


class QueryResultResponse(ResultResponse):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def list_response(self, data):
        return JsonResponse({
            "success": self.flag,
            "code": self.code,
            "message": self.msg,
            "data": data
        }, safe=False, json_dumps_params={'ensure_ascii': False})

    def query_response(self, pagination, data):
        return JsonResponse({
            "success": self.flag,
            "code": self.code,
            "message": self.msg,
            "data": {
                "total": pagination.page.paginator.count,
                "next": pagination.get_next_link(),
                "previous": pagination.get_previous_link(),
                "result": data
            }
        }, safe=False, json_dumps_params={'ensure_ascii': False})


def Success(msg='操作成功'):
    """操作成功"""
    return ResultResponse(msg=msg).response


def CommonResponse(model, serializer):
    """
    返回单体数据
    :param model: 数据实体
    :param serializer: 序列化类
    :return:
    """
    return ResultResponse().data_response(data=serializer(model).data)


def dataResponse(data):
    """
    返回列表数据
    :param data:
    :return:
    """
    return QueryResultResponse().list_response(data=data)


def ListResponse(queryset, serializer):
    """
    返回列表数据
    :param queryset: 查询集合结果
    :param serializer: 序列化类
    :return:
    """
    return QueryResultResponse().list_response(data=serializer(instance=queryset, many=True).data)


def QueryResponse(queryset, serializer, request, view):
    """
    返回分页列表数据
    :param queryset: 查询集合结果
    :param serializer: 序列化类
    :param request: request对象
    :param view 视图实体
    :return:
    """
    page = PagePagination()
    result = page.paginate_queryset(queryset=queryset, request=request, view=view)
    data = serializer(instance=result, many=True).data
    return QueryResultResponse().query_response(pagination=page, data=data)
